"""
结果显示组件
负责显示检测结果和统计信息
"""

import json
from datetime import datetime
from pathlib import Path

from PySide6.QtWidgets import (
    QWidget, QVBoxLayout, QHBoxLayout, QTableWidget, 
    QTableWidgetItem, QLabel, QPushButton, QHeaderView, QMessageBox
)
from PySide6.QtCore import Qt, Signal
from PySide6.QtGui import QFont


class ResultDisplayWidget(QWidget):
    """
    结果显示组件
    
    功能：
    - 显示检测结果列表
    - 显示统计信息
    - 导出结果
    """
    
    def __init__(self):
        super().__init__()
        self.results = []
        self.init_ui()
        
    def init_ui(self):
        """初始化界面"""
        layout = QVBoxLayout(self)
        
        # 标题
        title_label = QLabel("检测结果")
        title_font = QFont()
        title_font.setPointSize(12)
        title_font.setBold(True)
        title_label.setFont(title_font)
        layout.addWidget(title_label)
        
        # 统计信息
        stats_layout = QHBoxLayout()
        
        self.total_label = QLabel("总计: 0 个")
        stats_layout.addWidget(self.total_label)
        
        self.avg_confidence_label = QLabel("平均置信度: 0.00")
        stats_layout.addWidget(self.avg_confidence_label)
        
        stats_layout.addStretch()
        
        # 清空按钮
        self.btn_clear = QPushButton("清空结果")
        self.btn_clear.clicked.connect(self.clear_results)
        stats_layout.addWidget(self.btn_clear)
        
        # 导出按钮
        self.btn_export = QPushButton("导出结果")
        self.btn_export.clicked.connect(self.export_results)
        stats_layout.addWidget(self.btn_export)
        
        layout.addLayout(stats_layout)
        
        # 结果表格
        self.table = QTableWidget()
        self.table.setColumnCount(4)
        self.table.setHorizontalHeaderLabels(["时间", "车牌号", "置信度", "位置"])
        
        # 设置表格样式
        header = self.table.horizontalHeader()
        header.setSectionResizeMode(QHeaderView.Stretch)
        
        layout.addWidget(self.table)
        
    def add_result(self, result):
        """添加检测结果"""
        self.results.append(result)
        self._update_table()
        self._update_statistics()
        
    def clear_results(self):
        """清空结果"""
        self.results.clear()
        self._update_table()
        self._update_statistics()
        
    def export_results(self):
        """导出结果到文件"""
        if not self.results:
            QMessageBox.information(self, "提示", "没有可导出的结果")
            return
            
        try:
            # 创建输出目录
            output_dir = Path("output")
            output_dir.mkdir(exist_ok=True)
            
            # 生成文件名
            timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
            filename = f"detection_results_{timestamp}.json"
            filepath = output_dir / filename
            
            # 导出数据
            export_data = {
                'export_time': datetime.now().isoformat(),
                'total_count': len(self.results),
                'results': self.results
            }
            
            with open(filepath, 'w', encoding='utf-8') as f:
                json.dump(export_data, f, ensure_ascii=False, indent=2)
                
            QMessageBox.information(
                self, "成功", f"结果已导出到: {filepath}"
            )
            
        except Exception as e:
            QMessageBox.critical(
                self, "错误", f"导出失败: {e}"
            )
            
    def _update_table(self):
        """更新表格显示"""
        self.table.setRowCount(len(self.results))
        
        for row, result in enumerate(self.results):
            # 时间
            time_item = QTableWidgetItem(result.get('timestamp', ''))
            self.table.setItem(row, 0, time_item)
            
            # 车牌号
            plate_item = QTableWidgetItem(result.get('plate_number', ''))
            self.table.setItem(row, 1, plate_item)
            
            # 置信度
            confidence = result.get('confidence', 0)
            confidence_item = QTableWidgetItem(f"{confidence:.3f}")
            self.table.setItem(row, 2, confidence_item)
            
            # 位置
            bbox = result.get('bbox', [0, 0, 0, 0])
            position_text = f"({bbox[0]}, {bbox[1]}, {bbox[2]}, {bbox[3]})"
            position_item = QTableWidgetItem(position_text)
            self.table.setItem(row, 3, position_item)
            
        # 滚动到最新结果
        if self.results:
            self.table.scrollToBottom()
            
    def _update_statistics(self):
        """更新统计信息"""
        total_count = len(self.results)
        self.total_label.setText(f"总计: {total_count} 个")
        
        if total_count > 0:
            avg_confidence = sum(
                result.get('confidence', 0) for result in self.results
            ) / total_count
            self.avg_confidence_label.setText(f"平均置信度: {avg_confidence:.3f}")
        else:
            self.avg_confidence_label.setText("平均置信度: 0.000") 